﻿using System;
using System.Collections.Generic;
using System.Text;
using Mpi.Common.Collections;
using Xeml.Document;

namespace Xeml.Sampling
{
    public class PositionColumnEmitter : ColumnEmitter
    {

        public override void Emit(Xeml.Document.Contracts.IDocument xemlDoc)
        {
            this._columns.Clear();
            foreach (TreeNode<StoryBase> sbNode in xemlDoc.StoryBoard)
            {
                ExtractCols(sbNode.Content);
            }
        }

        private void ExtractCols(StoryBase storyBase)
        {
            Dictionary<string, VariableTerm> dict = new Dictionary<string, VariableTerm>();
            foreach (var obp in storyBase.ObservationPoints)
            {
                foreach (var ob in obp.Observations)
                {
                    foreach (var part in ob.Partitions)
                    {
                        foreach (VariableTerm term in part.Positions)
                        {
                            string id = term.NameSpaceAlias + term.TermId;
                            if (!dict.ContainsKey(id))
                                dict.Add(id, term);
                        }
                    }
                }
            }

            foreach (var item in dict)
            {
                PositionColumn pc = new PositionColumn();
                pc.ColumnLevel = ParameterColumnLevel.Parameter;
                pc.DataType = typeof(string);
                pc.Term = item.Value;
                pc.IsContainerColumn = true;
                pc.Enabled = true;

                if (!this._columns.ContainsKey(pc.Name))
                    this._columns.Add(pc.Name, pc);
                else
                    pc = (PositionColumn)this._columns[pc.Name];

                foreach (var ctxt in item.Value.ContextList())
                {
                    PositionColumn subpc = new PositionColumn();
                    subpc.Term = item.Value;
                    subpc.Context = ctxt;
                    subpc.DataType = typeof(string);
                    subpc.Enabled = true;
                    subpc.ColumnLevel = ParameterColumnLevel.Context;

                    if (!pc.SubColumns.ContainsKey(subpc.Name))
                        pc.SubColumns.Add(subpc.Name, subpc);
                }
            }
        }

        public PositionColumnEmitter()
        {
            base._columns = new Dictionary<string, Column>();
            base.name = "Positioning";
        }
    }
}
